import {type ReactNode, useEffect, useReducer} from "react";
import {CounterReducer} from "./reducer.ts";
import {CounterContext} from "./context.ts";
import {InitialState, KEY} from "./state.ts";

export const CounterProvider =
    ({children}: { children: ReactNode }) => {
        const [state, dispatch] = useReducer(CounterReducer, undefined, InitialState);

        useEffect(() => {
            localStorage.setItem(KEY, JSON.stringify(state));
        }, [state]);

        return (
            <CounterContext.Provider value={{state, dispatch}}>
                {children}
            </CounterContext.Provider>
        );
    };